<template>
    <div class="mainwrap-list" :class="{'noFixed':noFixed}">
        <div ref="myMain" class="my-main">
            <div ref="myContent"  :style="bodyStyle">
                <slot/>
                <div class="btmsg" v-if="loading">
                        <van-loading size="14px" v-if="!end && pageIndex!=1">loading...</van-loading>
                        <span class="noData" v-else-if="showOverTxt">{{overText||'In The End'}}</span>
                        <!-- <span class="noData" v-if="end && showOverTxt">{{overText||'In The End'}}</span> -->
                </div>
            </div>
        </div>
        <div class="my-footer"><slot name="footer"/></div>
    </div>
</template>

<script>
import { reactive,toRefs,onMounted,getCurrentInstance,computed } from "vue";
import { Loading  as vanLoading } from "vant";
import { useStore } from 'vuex'
import {H5CallAPPFuction} from '@/utils/common'
import back from "@/components/back.vue";
export default {
    props:{
        loading:{ // 是否开启盾冬到底部加载更多
            type:Boolean,
            default:()=>false // 默认不开启
        },
        showOverTxt:{ // 是否显示已经"
            type:Boolean,
            default:()=>true // 默认不开启
        },
        offset:{  // 滚动条距离底部的距离小于该值就触发加载更多
            type:Number,
            default: 60
        },
        end:{  // 数据全部加载完成标志
            type:Boolean,
            default: false
        }, 
        load:Function,  //加载数据，由组件调用者传入， 此函数必须返回一个Promise对象
        overText:{
            type:String,
            default:'--In The End--'
        },
        type:Number,
        outOnScroll:Function,  // 滚动监听，调用者可能需要监听滚动的高度等
        showback:{
            type:Boolean,
            default:true
        },
        bodyStyle:Object,
        bodyBg:String,
        noFixed:{  // mainwrap不使用Fixed定位
            type:Boolean,
            default:false 
        },
        pageIndex:{
            type:Number,
            default: 1
        }
    },
    components:{
        vanLoading,
        back
    },
    emits:{  // 出发事件需要emits申明（vue3+）
        'getUserInfoOver':null,
        'eleLoadOver':null
    },

    setup(props,context){
        const {proxy} = getCurrentInstance()
        const store = useStore()

        const state = reactive({
            wrap:null,
            con:null,
            statusBarHeight:computed(()=>store.state.base.statusBarHeight)
        })

        onMounted(()=>{
            // 添加app调用方法，获取头部状态栏高度，用于刘海屏全屏下，网页距离头部的高度，以免网页头部被手机状态栏遮挡
            window['getStatusBarHeight'] = function (statusBarHeight) {
                store.commit('arApi/set_statusBarHeight',statusBarHeight)
                //document.getElementById('mainwrap').style.paddingTop = statusBarHeight +'px'
            }
            // App调用，保存定位信息
            window['getNowLatitudeLongitude'] = function (lat,long,name) {
                store.commit('base/set_currentPosition',{
                    lat,
                    lng:long,
                    location:name
                })
            }
            // App调用，发送钱包信息
            window['sendWalletInfo'] = function (objStr) {
                store.commit('base/set_userInfo',objStr)
                context.emit('getUserInfoOver')
            }

            //setTimeout(()=>{
               // window.getStatusBarHeight(20)
                try {
                    H5CallAPPFuction('jsLoadComplete')  // 调用app的jsLoadComplete方法,通知app，H5页面加载了
                    H5CallAPPFuction('getWalletInfo')  // 调用app的getWalletInfo方法,通知app，
                } catch (error) {
                    console.log("调用app的jsLoadComplete出错了：不是在app环境中调用")
                   // setTimeout(()=>{sendWalletInfo({"walletAddress":"0x82CF3c0343918C8F174a9858A5C9A073c62Bc61f"})},1000)
                }
            //},500)
 
            context.emit('eleLoadOver',{ele:proxy.$refs.myMain})  // 把元素传出去
            if(props.loading && !props.end){
                state.wrap = proxy.$refs.myMain 
                state.con = proxy.$refs.myContent
                //setTimeout(()=>{
                    //this.onBottomLoadInit()
                    state.wrap.onscroll = ()=>{
                        onBottomLoadInit()
                    }
                //},1000) 
            }
        })

        const initScroll = ()=>{
            state.wrap.onscroll = onBottomLoadInit
        }
        const stopScroll = ()=>{
            state.wrap.onscroll = null
        }

        const onBottomLoadInit = async () =>{
            const wrap_h = state.wrap.offsetHeight 
            const con_h = state.con.offsetHeight
            const wrap_sh = state.wrap.scrollTop
            // console.log("11:",con_h - wrap_h - wrap_sh)
            // console.log("22:",props.offset)
            props.outOnScroll && props.outOnScroll(wrap_sh) // 如果调用者有滚动监听，则返回滚动高度
            if((con_h - wrap_h - wrap_sh) <=  props.offset){
                //console.log("触发了")
                state.wrap.onscroll = null
                await props.load()
                if(!props.end){
                    state.wrap.onscroll = onBottomLoadInit
                }else if(props.outOnScroll){ // 表示数据加载完（即到底部了），判断是否onscroll，有的话从添加监听
                    state.wrap.onscroll = ()=>{
                        props.outOnScroll(state.wrap.scrollTop) // 参数为滚动的高度
                    }
                }
            }
        }

        return {
            ...toRefs(state),
            initScroll,
            stopScroll
        }
    }
}
</script>

<style lang="scss" scoped>
    .mainwrap-list{
        position: fixed;
        z-index: 100;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        display: flex;
        flex-flow: column;
        &.backStyle{
            padding-left: 105px;
        }
        &.noFixed{
            position:static;
            &.backStyle{
                padding-left: 0;
            }
        }
        .my-main{
            flex:1;
            overflow: hidden;
            overflow-y: auto;
            -webkit-overflow-scrolling : touch; 
            flex-grow: 1;
            .btmsg{
                text-align: center;
                padding: 0 0 30px 0;
            }
            .noData{
                display: block;
                color:#999;
                text-align: center;
            }
        }
        &.allhgwrap{
            .my-content{
                height: 100%;
                overflow: hidden;
            }
        }
    }
    // @supports ((height: constant(safe-area-inset-top)) or (height: env(safe-area-inset-top))) and (-webkit-overflow-scrolling: touch) {
    // .mainwrap {
    //         padding-top: 20;
    //         padding-top: constant(safe-area-inset-top)!important;
    //         padding-top: env(safe-area-inset-top)!important;

    //         padding-bottom: 0;
    //         padding-bottom: costant(safe-area-inset-bottom)!important;
    //         padding-bottom: env(safe-area-inset-bottom)!important;
    //     }
    // }
</style>